// pages/person/person.js

const app =getApp()
var util = require('../../utils/util.js');
const GetPeriod = require("../../utils/getperiod.js");


Page({
  /* 页面的初始数据*/
  data: {
    userInfo: { avatarUrl:'../img/moren.jpg'},
    form: { phoneNumber: '',},
    time:'',
    reason:'',
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    apartmentName:'',
    nowStatus:'上班',
    showModalStatus: false,
    sbshow:'',
    xbshow:'',
 
    displaySta: 'none',
    counter:'',
    totalAmount:'',
    attentionContent:'',
    confirmSta:'',
    yanzhengOk:'none',
    yanzhengFail:'block',
    changeS:'dayshang',
    changeX:'dayxia',

    dateType: 0,
    dateTypeR: 'now',
    startDate: '',
    endDate: '',
  },
  phoneInput:function(e){
    this.setData({
      phoneNumber: e.detail.value
    }) 
  },
  btnclick: function () {
    var mobile = this.data.phoneNumber;
    var phonetel = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (mobile == '') {
      wx.showModal({
        title: '填写错误',
        content: '手机号不能为空',
        showCancel: false,
      })
      return false
    }
    else if (mobile.length != 11) {
      wx.showModal({
        title: '填写错误',
        content: '手机号长度有误',
        showCancel: false,
      })
      return false;
    }
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!myreg.test(mobile)) {
      wx.showModal({
        title: '填写错误',
        content: '手机号有误',
        showCancel: false,
      })
      return false;
    }
    return true;
  },

  zhankai: function () {
    if (this.data.displaySta == 'none') {
      this.setData({
        displaySta: 'block'
      })
    } else {
      this.setData({
        displaySta: 'none'
      })
    }
  },
  refresh: function () {
    var point = this
    this.getOrder(this.data.startDate, this.data.endDate, point)
  },
  preparePeisong:function(){

  },
 
  /**
   * 生命周期函数--监听页面加载
   */                                                                                                                                                                            
  onLoad: function (options) {

    this.time = new GetPeriod();
    this.setData({ dateType: 0, startDate: this.time.getNowDate(), endDate: this.time.getNowDate() });
    console.log(this.data.startDate)
    var point = this
    
    var point = this
    if(app.globalData.confirmSta){
      point.getOrder(point.data.startDate, point.data.endDate, point)
        point.setData({
          yanzhengOk: 'block',
          yanzhengFail: 'none'
        })
    }
    this.setData({
      peisongIng: app.globalData.peisongIng,
      peisongCompleted: app.globalData.peisongCompleted,
      waitRenling: app.globalData.waitRenling,
      confirmSta: app.globalData.confirmSta,
      apartmentName: app.globalData.apartmentName,
    })
    console.log()
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true,
          })
        }
      })
    }
    console.log('当前工作状态' + getApp().globalData.workStatus)
    if (getApp().globalData.workStatus == app.globalData.shangbanStatus) {
      this.setData({
        nowStatus: '上班',
        sbshow: 'none'
      })
    } else {
      this.setData({
        nowStatus: '下班',
        xbshow: 'none',
      })
    } 
  }, 
  getUserInfo: function (e) {
      console.log(e)
      const point = this
      app.globalData.userInfo = e.detail.userInfo
      
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      }),
        console.log("用户输入的电话号码为：" + this.data.phoneNumber);
      //console.log("用户信息"+this.data.userInfo)
        if(this.btnclick()){
          this.send()
        }
  },
  send:function(){
    var point = this
    var userType = app.globalData.userType
    wx.login({
      success: res => {
        // ------ 获取凭证 ------
        var code = res.code;
        if (code) {
          console.log('获取用户登录凭证：' + code);
          // ------ 发送凭证 ------
          wx.request({
            url: 'https://www.cycs023.cn/f50m-web/api/login',
            data: {
              code: code,
              userType: userType,
              avatarUrl: this.data.userInfo.avatarUrl,
              nickName: this.data.userInfo.nickName,
              gender: this.data.userInfo.gender,
              language: this.data.userInfo.language,
              city: this.data.userInfo.city,
              province: this.data.province,
              country: this.data.country,
              phoneNumber: this.data.phoneNumber
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              point.setData({
                attentionContent: res.data.meta.message,
              })
              app.globalData.confirmSta = res.data.meta.success
              if (res.data.meta.success) {
                console.log("获取到的token为：" + res.data.data.token)
                getApp().globalData.token = res.data.data.token
                // that.globalData.openid = res.data
                //wx.setStorageSync('openid', res.data)
                wx.showToast({
                  title: '验证成功',
                  icon: 'success',
                  duration: 1000
                })
                point.setData({
                  yanzhengFail:'none',
                  yanzhengOk:'block',
                })
                app.globalData.confirmSta = res.data.meta.success
                wx.request({
                  url: 'https://www.cycs023.cn/f50m-web/api/dictorys',
                  method: 'GET',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'X-SDX-Token': res.data.data.token
                  },
                  data: {
                    pId: 4
                  },
                  success:function(res){
                    console.log(res);
                    app.globalData.shangbanStatus = res.data.data[0].id;
                    app.globalData.shangbanName = res.data.data[0].name;
                    app.globalData.xiabanStatus = res.data.data[1].id;
                    app.globalData.xiabanName = res.data.data[1].name;
                    console.log("当前上班字典值：" + app.globalData.shangbanStatus);
                    console.log("当前下班字典值：" + app.globalData.xiabanStatus)
                    wx.request({
                      url: 'https://www.cycs023.cn/f50m-web/api/dictorys',
                      method: 'GET',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded',
                        'X-SDX-Token': getApp().globalData.token
                      },
                      data: {
                        pId: 7
                      },
                      success: function (res) {
                        console.log(res);
                        app.globalData.peisongIng = res.data.data[4].id;
                        app.globalData.peisongCompleted = res.data.data[5].id;
                        if (res.statusCode == 200) {
                          wx.request({
                            url: 'https://www.cycs023.cn/f50m-web/api/dictorys',
                            method: 'GET',
                            header: {
                              'content-type': 'application/x-www-form-urlencoded',
                              'X-SDX-Token': getApp().globalData.token
                            },
                            data: {
                              pId: 13
                            },
                            success: function (res) {
                              console.log(res);
                              app.globalData.notify = res.data.data[0].id;
                              app.globalData.notifyName = res.data.data[0].name;
                            }
                          })
                        }
                      }
                    })
                  }
                })
                wx.request({
                  url: 'https://www.cycs023.cn/f50m-web/api/riderworks',
                  method: 'GET',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'X-SDX-Token': res.data.data.token
                  },
                  success:function(res){
                    if(res.data.meta.success){
                      point.setData({
                        apartmentName: res.data.data.rows[0].apartmentName
                      })
                      app.globalData.apartmentName = point.data.apartmentName
                      console.log('当前工作状态' + res.data.data.rows[0].workStatus)
                      if (res.data.data.rows[0].workStatus == app.globalData.shangbanStatus) {
                        point.setData({
                          nowStatus: '上班',
                          sbshow: 'none',
                          xbshow: 'inline-block'
                        })
                      } else {
                        point.setData({
                          nowStatus: '下班',
                          xbshow: 'none',
                          sbshow: 'flex'
                        })
                      } 
                    }
                    if (res.data.data.rows[0].workStatus == app.globalData.shangbanStatus) {
                      app.globalData.workStatus = res.data.data.rows[0].workStatus;
                      app.globalData.workStatusName = '上班'
                    } else {
                      app.globalData.workStatus = res.data.data.rows[0].workStatus;
                      app.globalData.workStatusName = '下班'
                    }
                    point.getOrder(point.data.date,point.data.date2,point)
                  }
                })
              } else {
                console.log(point.data.attentionContent)
                wx.showModal({
                  title: '验证失败',
                  content: point.data.attentionContent,
                  showCancel: false,
                  confirmText: '是',
                })
                app.globalData.confirmSta = res.data.meta.success
                point.setData({
                  yanzhengFail: 'block',
                  yanzhengOk: 'none',
                })
              }
            },
          })
        } else {
          console.log('获取用户登录失败：' + res.errMsg);
        }
      }
    })
  },

  
  gotoSetting :function(){
    wx.navigateTo({
      url: '../info/info',
    })
  },



  timeInput:function(e){
    this.setData({
      time:e.detail.value
    })
    console.log('请假时间' + this.data.time)
  },
  reasonInput:function(e){
    this.setData({
      reason: e.detail.value
    })
    console.log('请假理由' + this.data.reason)
  },
 



  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例  
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });
    // 第2步：这个动画实例赋给当前的动画实例 
    this.animation = animation;
    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();
    // 第4步：导出动画对象赋给数据对象储存 
    this.setData({
      animationData: animation.export()
    })
    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function () {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      this.setData({
        animationData: animation
      })
      //关闭 
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)
    // 显示 
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }
  },
  shangban:function(){
    var that = this;
    var token = app.globalData.token
    var shangbanCode = app.globalData.shangbanStatus
    console.log("shangbancode:"+shangbanCode)
    console.log("our token is:" + token)
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/riderworks',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'X-SDX-Token': token
      },
      success: function (res) {
        console.log(res.data.data.rows[0].id);
        wx.request({
          url: 'https://www.cycs023.cn/f50m-web/api/riderworks/' + res.data.data.rows[0].id + '/',
          method: 'PUT',
          header: {
            'content-type': 'application/json',
            'X-SDX-Token': token
          },
          data: {
            workStatus: shangbanCode,
            riderId: res.data.data.rows[0].riderId,
          },
          success: function (res) {
                //console.log("获取到的token为：" + res.data.data.token)
                //getApp().globalData.token = res.data.data.token
                // that.globalData.openid = res.data
                //wx.setStorageSync('openid', res.data)
                if(res.data.meta.success){
                  that.setData({
                    nowStatus: '上班',
                    workStatus: 'sb',
                    buttonType: 'warn',
                    sbshow: 'none',
                    xbshow: 'inline-block'
                  })
                  app.globalData.workStatus == shangbanCode
                  wx.showModal({
                    title: '成功',
                    content: res.data.meta.message,
                    showCancel:false,
                  })
                }else{
                  wx.showModal({
                    title: '失败',
                    content: res.data.meta.message,
                    showCancel:false,
                  })
                }
                
          }
        })
      },
    }) 
  },
  parePeisong:function(){
    var that = this;
    var token = app.globalData.token
    var xiabanCode = app.globalData.xiabanStatus
 
    var attention = app.globalData.notify
    console.log("our token is:" + token)
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/riderworks',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'X-SDX-Token': token
      },
      success: function (res) {
        console.log(res.data.data.rows[0].id);
        wx.request({
          url: 'https://www.cycs023.cn/f50m-web/api/riderworks/' + res.data.data.rows[0].id + '/',
          method: 'PUT',
          header: {
            'content-type': 'application/json',
            'X-SDX-Token': token
          },
          data: {
            riderId: res.data.data.rows[0].riderId,
            notify: attention
          },
          success: function (res) {
            if(res.statusCode == 200){
              app.globalData.workStatus = xiabanCode
              console.log(getApp().globalData.workStatus)
              wx.showToast({
                title: '准备配送成功',
                icon: 'success',
                duration: 1000
              })
            }
          }
        })

      },
    })
  },
  xiaban: function () {
    var that = this;
    var token = app.globalData.token
    var xiabanCode = app.globalData.xiabanStatus
    console.log("our token is:" + token)
    if (that.data.time !== "" && that.data.reason !== ""){
      wx.request({
        url: 'https://www.cycs023.cn/f50m-web/api/riderworks',
        method: 'GET',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'X-SDX-Token': token
        },
        success: function (res) {
          console.log(res.data.data.rows[0].id);
          wx.request({
            url: 'https://www.cycs023.cn/f50m-web/api/riderworks/' + res.data.data.rows[0].id + '/',
            method: 'PUT',
            header: {
              'content-type': 'application/json',
              'X-SDX-Token': token
            },
            data: {
              workStatus: xiabanCode,
              offTime: that.data.time,
              offReason: that.data.reason,
              riderId: res.data.data.rows[0].riderId,
            },
            success: function (res) {

              //console.log("获取到的token为：" + res.data.data.token)
              //getApp().globalData.token = res.data.data.token
              // that.globalData.openid = res.data
              //wx.setStorageSync('openid', res.data)
              that.setData({
                showModalStatus: false,
                nowStatus: '下班',
                workStatus: 'xb',
                sbshow: 'flex',
                xbshow: 'none',
              })
              app.globalData.workStatus = xiabanCode
              console.log(getApp().globalData.workStatus)
              wx.showModal({
                title: '成功',
                content: res.data.meta.message,
                showCancel:false,
              })
            }
          })

        },
      })
    }else{
      wx.showModal({
        title: '下班失败',
        content: '请检查原因和时间是否填写正确',
        showCancel : false,
      })
    }
    
  },

  testSubmit: function (e) {
    let formId = e.detail.formId;
    this.dealFormIds(formId); //处理保存推送码
    console.log(formId)
    let type = e.detail.target.dataset.type;
    var token = app.globalData.token
    //根据type的值来执行相应的点击事件
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/formids/',
      data: {
        formId: formId
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'X-SDX-Token': token
      },
      success: function (res) {
        if (res.statusCode == 200) {
          console.log('success')
        }
      }
    })
  },
  dealFormIds: function (formId) {
    let formIds = app.globalData.gloabalFomIds;//获取全局数据中的推送码gloabalFomIds数组
    if (!formIds) formIds = [];
    let data = {
      formId: formId,
      expire: parseInt(new Date().getTime() / 1000) + 604800 //计算7天后的过期时间时间戳
    }
    formIds.push(data);//将data添加到数组的末尾
    app.globalData.gloabalFomIds = formIds; //保存推送码并赋值给全局变量
  },
  getOrder: function (start_date, end_date, point) {
      var token = app.globalData.token
      var that = this
      var ids = new Array()
      console.log("our token is:" + token)
      wx.showLoading({
        title: '加载中....',
      })
      wx.request({
        url: 'https://www.cycs023.cn/f50m-web/api/orders/statistics/' + app.globalData.peisongCompleted,
        data: {
          createStartTime: point.data.startDate + " 00:00:00",
          createEndTime: point.data.endDate + " 23:59:59",
          flag: 0,
        },
        method: 'GET',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'X-SDX-Token': token
        },
        success: function (res) {
          if (res.statusCode == 200) {
            point.setData({
              counter: res.data.data.rows[0].orderNum,
              totalAmount: res.data.data.rows[0].totalAmount
            })
            console.log(point.data.totalAmount)
          }
        }
      })
      console.log(point.data.orderInfo)
      wx.hideLoading();
   
  },
  getDateType(e) {
    let dateType = e.currentTarget.dataset.datetype;
    let startDate = '', endDate = '';
    var point = this;
    if (dateType == 0) {//今天
      startDate = this.time.getNowDate();
      endDate = this.time.getNowDate();
      this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
      this.getOrder(startDate,endDate, point)
      
      console.log(startDate + "~" + endDate)
    } else if (dateType == 1) {//本周
      startDate = this.time.getWeekStartDate();
      endDate = this.time.getWeekEndDate();
      this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 2) {//本月
      startDate = this.time.getMonthStartDate();
      endDate = this.time.getMonthEndDate();
      this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 3) {//本年
      startDate = this.time.getYearStartDate();
      endDate = this.time.getYearEndDate();
      this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 4) {//选择时段初始化为当天时间段
      startDate = this.time.getNowDate();
      endDate = this.time.getNowDate();
      this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 5) {//本季度
      startDate = this.time.getQuarterStartDate();
      endDate = this.time.getQuarterEndDate();
      this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    }
  },
  bindDateChange(e) {
    var point = this
    if (e.currentTarget.id == 'start') {
      this.setData({ startDate: e.detail.value })
      this.getOrder(this.data.startDate, this.data.endDate, point)
    } else if (e.currentTarget.id == 'end') {
      this.setData({ endDate: e.detail.value })
      this.getOrder(this.data.startDate, this.data.endDate, point)
    } else {
      return;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
 
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  globalData:{
    phoneNum:''
  }
})